package com.msk.sys.utils;



import com.msk.common.utils.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 功能：pdf转换工具
 * 作者：Zhang_XinGang
 * 时间：2020/2/17 21:33
 */
public class PdfUtil {
    
    /**
     * 将标准word转换为pdf
     * window环境调用jacob控件
     * linux环境调用aspose控件
     * @param wordPath
     * @return
     */
    public static String wordToPdf(String wordPath){
        long start = System.currentTimeMillis();
        String pdfPath = null;
        String mkdir = getFileTemporary();
        if(StringUtils.isNotEmpty(wordPath)){
            String tempWord = null;
            if(wordPath.startsWith("http://")){
                tempWord = downloadFile(wordPath);
            }else{
                tempWord = wordPath;
            }
            /*if(isWindows()){
                pdfPath = JacobUtils.wordToPdf(tempWord,mkdir);
            }else if(isLinux()){
                //linux采用 aspose控件
                pdfPath = AsposeUtils.wordToPdf(tempWord,mkdir);
            }*/
            pdfPath = AsposeUtils.wordToPdf(tempWord,mkdir);
            if(wordPath.startsWith("http://")){
                File file = new File(tempWord);
                file.delete();
            }
        }
        long end = System.currentTimeMillis();
        System.out.println("转换耗时："+(end-start));
        return pdfPath;
    }

    /**
     * 给word添加图片水印
     * @param wordPath
     * @param imgPath
     * @return
     */
    public static String wordInsertImageWatermark(String wordPath,String imgPath){
        if(StringUtils.isEmpty(wordPath) || StringUtils.isEmpty(imgPath)){
            return null;
        }
        String tempWord = null;
        if(wordPath.startsWith("http://")){
            tempWord = downloadFile(wordPath);
        }else{
            tempWord = wordPath;
        }
        File file = new File(tempWord);
        if(!file.exists()){
            return null;
        }
        String tempImg = null;
        if(imgPath.startsWith("http://")){
            tempImg = downloadFile(imgPath);
        }else{
            tempImg = imgPath;
        }
        File fileImg = new File(tempImg);
        if(!fileImg.exists()){
            return null;
        }
        String newDoc = AsposeUtils.wordInsertWatermark(tempWord,tempImg);
        if(wordPath.startsWith("http://")) {
            file.delete();
        }
        if(imgPath.startsWith("http://")){
            fileImg.delete();
        }

        return newDoc;
    }

    /**
     * 获取临时目录
     * @return
     */
    private static String getTemporary(){
        String classesPath = SystemPath.getJavaClassPath();
        SimpleDateFormat format2 = new SimpleDateFormat("yyyyMMdd");
        String filePath = classesPath.replace("/WEB-INF/classes/","") + "/temporary/" + format2.format(new Date());
        //String filePath = "F:/javaEEWork/liangfang20200203/liangfang/target/temporary/20200217";

        File file = new File(filePath);
        if(!file.exists()){
            file.mkdirs();
        }
        return filePath;
    }

    /**
     * 获取临时目录
     * @return
     */
    private static String getFileTemporary(){
        String classesPath = SystemPath.getJavaClassPath();
        String prePath = classesPath.replace("/WEB-INF/classes/","");
        if (!prePath.endsWith("/")) {
            prePath = prePath + "/";
        }
        String filePath = prePath + "/userfiles/".substring(1) + DateFormatUtils.format(new Date(), "yyyyMM");
        File file = new File(filePath);
        if(!file.exists()){
            file.mkdirs();
        }
        return filePath;
    }

    /**
     * 下载临时文件
     * @param fileUrl
     * @return
     */
    public static String downloadFile(String fileUrl){
        String filePath = null;
        int bytesum = 0;
        int byteread = 0;
        try {
            filePath = getTemporary();

            String[] paths = fileUrl.split("/");
            String fileName = paths[paths.length-1];
            if(paths[paths.length-1].indexOf("\\?")>-1){
                fileName = paths[paths.length-1].split("\\?")[0];
            }
            filePath = filePath + "/" + fileName;
            URL url = new URL(fileUrl);
            URLConnection conn = url.openConnection();
            InputStream inStream = conn.getInputStream();
            FileOutputStream fs = new FileOutputStream(filePath);
            byte[] buffer = new byte[1204];
            while ((byteread = inStream.read(buffer)) != -1) {
                bytesum += byteread;
                fs.write(buffer, 0, byteread);
            }
            inStream.close();
            fs.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return filePath;
    }
    public static boolean isWindows(){
        String os = System.getProperty("os.name").toLowerCase();
        return os.indexOf("windows")>=0;
    }
    public static boolean isLinux(){
        String os = System.getProperty("os.name").toLowerCase();
        return os.indexOf("linux")>=0;
    }
}
